package com.sskj.fca.ui.activity;


import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.TipMineUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.fca.R;
import com.sskj.fca.bean.MainMenuBean;
import com.sskj.fca.bean.NewNoticeBean;
import com.sskj.fca.bean.UpdataBean;
import com.sskj.fca.bean.rxbus.LogoutBean;
import com.sskj.fca.bean.rxbus.MainChangeTabBean;
import com.sskj.fca.component.DaggerUserDataComponent;
import com.sskj.fca.presenter.MainActivityPresenter;
import com.sskj.fca.ui.MainPopup;
import com.sskj.fca.ui.fragment.AppUpDateFragment;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

@Route(path = RConfig.APP_MAIN)
public class MainActivity extends BaseActivity<MainActivityPresenter> {
    @BindView(R.id.tv_main_title)
    TextView tvMainTitle;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.tv_mine)
    TextView tv_mine;
    @BindView(R.id.iv_red_point)
    ImageView iv_red_point;
    @BindView(R.id.ivToggle)
    ImageView ivToggle;
    @BindView(R.id.rl_bg)
    RelativeLayout rl_bg;
    @BindView(R.id.rl_right_top)
    RelativeLayout rl_right_top;
    @BindView(R.id.ivPhoto)
    RelativeLayout ivPhoto;
    @BindView(R.id.rl_main_pop)
    RelativeLayout rl_main_pop;
    @BindView(R.id.rlNotice)
    RelativeLayout rlNotice;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @BindView(R.id.ivLogo)
    ImageView ivLogo;
    @BindView(R.id.iv_main_head)
    ImageView iv_main_head;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recyclerView_popup)
    RecyclerView recyclerViewPopup;
    @BindView(R.id.llLeft)
    LinearLayout llLeft;
    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;
    @Inject
    UserViewModel userViewModel;
    private Fragment currentFragment;
    private Fragment qiangJinFragment;
    private Fragment helpCenterFragment;
    private Fragment theAgentFragment;
    private Fragment downLoadFragment;
    private Fragment rollFragment;

    private MainPopup mainPopup;
    private MaterialDialog loginTip;
    private UserData userData;
    private ObjectAnimator animator;
    private SlimAdapter popSlimAdapter;
    private ArrayList<String> mainMenuBeans;
    private boolean mActivityIsCreate = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_main;
    }

    @Override
    public MainActivityPresenter getPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mPresenter.isHaveNoticeList();
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
            if (userData == null) {
                iv_main_head.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_logo));
                rlNotice.setVisibility(View.GONE);
                tv_mine.setVisibility(View.GONE);
                tv_login.setVisibility(View.VISIBLE);
                rl_right_top.setVisibility(View.GONE);
            } else {
                mPresenter.getUserInfo();
                rlNotice.setVisibility(View.VISIBLE);
                tv_mine.setVisibility(View.VISIBLE);
                tv_login.setVisibility(View.GONE);
                rl_right_top.setVisibility(View.VISIBLE);
            }
            mainMenuBeans = new ArrayList<>();
//            mainMenuBeans.add("战绩");
            mainMenuBeans.add("我的资产");
            mainMenuBeans.add("安全设置");
            mainMenuBeans.add("通知中心");
            mainMenuBeans.add("支付密码");
            mainMenuBeans.add(userData == null ? "登录" : "退出");
            popSlimAdapter.updateData(mainMenuBeans);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mActivityIsCreate) {
            mPresenter.initWebSocket();
            mActivityIsCreate = false;
        }
    }

    @Override
    protected void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.getUserInfo();
            } else {
                userData = null;
            }
            if (userData == null) {
                rlNotice.setVisibility(View.GONE);
                tv_mine.setVisibility(View.GONE);
                tv_login.setVisibility(View.VISIBLE);
                rl_right_top.setVisibility(View.GONE);
            } else {
                rlNotice.setVisibility(View.VISIBLE);
                tv_mine.setVisibility(View.VISIBLE);
                tv_login.setVisibility(View.GONE);
                rl_right_top.setVisibility(View.VISIBLE);
            }
            initRightPop();
            mainMenuBeans = new ArrayList<>();
//            mainMenuBeans.add("战绩");
            mainMenuBeans.add("我的资产");
            mainMenuBeans.add("安全设置");
            mainMenuBeans.add("通知中心");
            mainMenuBeans.add("支付密码");
            mainMenuBeans.add(userData == null ? "登录" : "退出");
            popSlimAdapter.updateData(mainMenuBeans);
        });
        mPresenter.isHaveNoticeList();
        mPresenter.updata(APKVersionCodeUtils.getVerName(this), false);
        initLeftMenu();
        changeToQiangjin();

        ClickUtil.click(ivToggle, () -> {
            if (drawerLayout.isDrawerOpen(Gravity.START)) {
                drawerLayout.closeDrawer(Gravity.START);
            } else {
                drawerLayout.openDrawer(Gravity.START);
            }
        });
        ClickUtil.click(rl_right_top, () -> {
            rl_main_pop.setVisibility(View.VISIBLE);
            rl_main_pop.setAlpha(0);
            rl_bg.setVisibility(View.VISIBLE);
            animator.start();
        });
        ClickUtil.click(rl_bg, () -> {
            rl_main_pop.setVisibility(View.GONE);
            rl_bg.setVisibility(View.GONE);
        });
        ClickUtil.click(rlNotice, () -> {
            ARouter.getInstance().build(RConfig.APP_NOTICE_CENTER_LIST).navigation();
        });
        ClickUtil.click(tv_login, () -> ARouter.getInstance().build(RConfig.APP_LOGIN).navigation());
    }

    private void initRightPop() {
        animator = ObjectAnimator.ofFloat(rl_main_pop, "alpha", 0f, 1f);
        animator.setDuration(500);
        recyclerViewPopup.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewPopup.addItemDecoration(new DividerLineItemDecoration(this)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        popSlimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_main_popup, new SlimInjector<String>() {
            @Override
            public void onInject(String data, IViewInjector injector, List payloads) {
                injector.text(R.id.tv_popup, data);
            }
        }).attachTo(recyclerViewPopup).updateData(mainMenuBeans);
        ItemClickSupport.addTo(recyclerViewPopup)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    rl_main_pop.setVisibility(View.GONE);
                    rl_bg.setVisibility(View.GONE);
                    if (position != 5 && userData == null) {
                        if (loginTip == null) {
                            loginTip = TipMineUtil.getTip(this, "请先登录", "去登录", () -> {
                                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                            });
                        }
                        loginTip.show();
                        return;
                    }
                    switch (position) {
//                        case 0://战绩
//                            ARouter.getInstance().build(RConfig.APP_USER_INFO).navigation();
//                            break;
                        case 0://我的资产
                            ARouter.getInstance().build(RConfig.APP_ASSET).navigation();
                            break;
                        case 1://安全设e置
                            ARouter.getInstance().build(RConfig.APP_SAFE_SETTING).navigation();
                            break;
                        case 2://通知中心
                            ARouter.getInstance().build(RConfig.APP_NOTICE_CENTER_LIST).navigation();
                            break;
                        case 3://支付密码
                            ARouter.getInstance().build(RConfig.APP_SET_PAY_PWD).navigation();
                            break;
                        case 4://退出
                            if (userData == null) {
                                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                            } else {
                                RxBus.getDefault().post(new LogoutBean());
                                LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
                                logoutProvider.logout();
                            }
                            break;
                    }
                });

    }

    private MainPopup showBalancePopList() {
        mainPopup = new MainPopup(this, userData);
        mainPopup.setMySelectPopupWindow(mainPopup);
        return mainPopup;
    }

    private void initLeftMenu() {
        ArrayList<MainMenuBean> mainMenuBeans = new ArrayList<>();
        mainMenuBeans.add(new MainMenuBean(R.mipmap.app_icon_menu_qiangjin, "FCA"));
//        mainMenuBeans.add(new MainMenuBean(R.mipmap.app_icon_menu_spread, "全民代理"));
        mainMenuBeans.add(new MainMenuBean(R.mipmap.app_icon_menu_agent, "我的推广"));
        mainMenuBeans.add(new MainMenuBean(R.mipmap.app_icon_question, "帮助中心"));
        mainMenuBeans.add(new MainMenuBean(R.mipmap.app_icon_menu_download, "APP下载"));
        mainMenuBeans.add(new MainMenuBean(R.mipmap.aoo_icon_updata, "版本升级"));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        SlimAdapter slimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_main_menu, new SlimInjector<MainMenuBean>() {
            @Override
            public void onInject(MainMenuBean data, IViewInjector injector, List payloads) {
                injector
                        .image(R.id.ivTitle, data.getRes())
                        .text(R.id.tvTitle, data.getContent())
                ;
            }
        }).attachTo(recyclerView).updateData(mainMenuBeans);
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    if (position == 1 && userData == null) {
                        if (loginTip == null) {
                            loginTip = TipMineUtil.getTip(this, "请先登录", "去登录", () -> {
                                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                            });
                        }
                        loginTip.show();
                        return;
                    }
                    switch (position) {
                        case 0://FCA
                            tvMainTitle.setText(App.INSTANCE.getString(R.string.app_name));
                            changeToQiangjin();
                            break;
//                        case 1://全民代理
//                            tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_the_agent));
//                            if (theAgentFragment == null) {
//                                theAgentFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_THE_AGENT).navigation();
//                            }
//                            switchFragment(theAgentFragment).commit();
//                            break;
                        case 1://我的推广
                            ARouter.getInstance().build(RConfig.APP_SPREAD).navigation();
                            break;
                        case 2://帮助中心
                            tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_help_center));
                            if (helpCenterFragment == null) {
                                helpCenterFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_HELP_CENTER).navigation();
                            }
                            switchFragment(helpCenterFragment).commit();
                            break;
                        case 3://APP下载
                            tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_download));
                            if (downLoadFragment == null) {
                                downLoadFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_APP_DOWMLOAD).navigation();
                            }
                            switchFragment(downLoadFragment).commit();
                            break;
                        case 4://版本升级
                            mPresenter.updata(APKVersionCodeUtils.getVerName(this), true);
                            break;
                    }
                    drawerLayout.closeDrawer(Gravity.START);
                });
    }

    public void isHaveNotice(NewNoticeBean newNoticeBean) {
        if (newNoticeBean.getOut_show_red().equals("0")) {
            iv_red_point.setVisibility(View.INVISIBLE);
        } else {
            iv_red_point.setVisibility(View.VISIBLE);
        }
    }

    private void changeToQiangjin() {
        if (qiangJinFragment == null) {
            qiangJinFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_QIANGJIN).navigation();
        }
        switchFragment(qiangJinFragment).commit();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(MainChangeTabBean mainTabChange) {
        tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_download));
        switch (mainTabChange.getPos()) {
            case 0:
                tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_help_center));
                helpCenterFragment = null;
                if (helpCenterFragment == null) {
                    helpCenterFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_HELP_CENTER)
                            .withString(Constans.POSITION, String.valueOf(mainTabChange.getPos())).navigation();
                }
                switchFragment(helpCenterFragment).commit();
                break;
            case 1:
                tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_help_center));
                helpCenterFragment = null;
                if (helpCenterFragment == null) {
                    helpCenterFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_HELP_CENTER)
                            .withString(Constans.POSITION, String.valueOf(mainTabChange.getPos())).navigation();
                }
                switchFragment(helpCenterFragment).commit();
                break;
            case 2:
                tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_help_center));
                helpCenterFragment = null;
                if (helpCenterFragment == null) {
                    helpCenterFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_HELP_CENTER)
                            .withString(Constans.POSITION, String.valueOf(mainTabChange.getPos())).navigation();
                }
                switchFragment(helpCenterFragment).commit();
                break;
            case 3:
                if (downLoadFragment == null) {
                    downLoadFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_APP_DOWMLOAD).navigation();
                }
                switchFragment(downLoadFragment).commit();
                break;
            case 7:
                tvMainTitle.setText(App.INSTANCE.getString(R.string.app_fragment_help_center));
                helpCenterFragment = null;
                if (helpCenterFragment == null) {
                    helpCenterFragment = (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_HELP_CENTER)
                            .withString(Constans.POSITION, String.valueOf(mainTabChange.getPos())).navigation();
                }
                switchFragment(helpCenterFragment).commit();
                break;
        }
    }

    private FragmentTransaction switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            transaction.add(R.id.frameLayout, targetFragment, targetFragment.getClass().getName()).show(targetFragment);
        } else {
            transaction.hide(currentFragment).show(targetFragment);
        }
        currentFragment = targetFragment;
        return transaction;
    }

    @Override
    protected void onDestroy() {
        mPresenter.closeWebSocket();
        mPresenter.closeTimeSocket();
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void updateUser(UserBean userBean) {
        if (TextUtils.isEmpty(userBean.getUpic())) {
            iv_main_head.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_logo));
        } else {
            ImageUtil.setCircleImage(BaseHttpConfig.BASE_URL + userBean.getUpic(), iv_main_head);
        }
    }

    public void checkUpdata(UpdataBean updataBean) {
        if (updataBean == null) {
            return;
        }
        String verName = APKVersionCodeUtils.getVerName(this);
        updataBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(updataBean.getVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, updataBean);
            appUpDateFragment.setArguments(bundle);
            fragmentTransaction.add(appUpDateFragment, "updateUI");
            fragmentTransaction.commitAllowingStateLoss();
        } else {
            ToastUtil.showShort("当前已是最新版本");
        }

    }

}
